import React, { Component } from 'react'
import { Card, Button, Table, Modal, Form, Input, message, Tree } from 'antd';
import dayjs from 'dayjs';
import { connect } from "react-redux"
import { PlusOutlined } from '@ant-design/icons';
import { reqRoleList, reqAddRole, reqAuthRole } from "../../api";
import { PAGE_SIZE } from "../../config/index"
import menuConfig from "../../config/menu_config"

const { Item } = Form
const { TreeNode } = Tree;

class Role extends Component {
    state = {
        isShowAdd: false,   // 模态框状态 ----- 添加角色
        isShowAuth: false,   // 模态框状态 ----- 权限
        roleList: [],
        total: '',      // 总共有多少项
        current:1,  // 当前页面(默认打开第1页)

        //一下为树组件的状态
        checkedKeys: ['home'],   //所有已选中的菜单
        menuList: menuConfig,
        _id: ''   //当前操作角色的id
    }

    componentDidMount() {
        this.getRoleList()
    }
    //从服务器拿到角色分页列表
    getRoleList = async (number = 1) => {     //注意：【这里巨坑!!!!】  要在形参这里把默认值确定好，下面直接number！
        let result = await reqRoleList(number, PAGE_SIZE)   //不要在这里给number设置默认值！
        const { status, data } = result
        console.log(data);
        if (status === 0) {
            this.setState({
                roleList: data.list,
                total:data.total,
                current:data.pageNum
            })
        }

    }


    //新增角色 ---- 弹窗
    showAddModal = () => {

        this.setState({
            isShowAdd: true,
        });

    };
    //新增角色 ---- ok
    handleAddOk = () => {
        //表单统一验证
        this.form.validateFields()
            .then(async (value) => {
                let result = await reqAddRole(value.roleName)
                const { status } = result
                if (status === 0) {
                    message.success('添加成功')
                    this.getRoleList()
                    this.setState({ isShowAdd: false })
                    this.form.resetFields()  //表单重置
                } else message.error('添加角色失败')
            })
            .catch(() => {
                message.error('输入项不能为空')
            })

    };
    handleAddCancel = () => {
        this.form.resetFields()
        this.setState({ isShowAdd: false });
    };



    //新增授权 ---- 弹窗
    showAuthModal = (_id) => {
        const { roleList } = this.state
        let result = roleList.find((item) => {
            return item._id === _id
        })
        this.setState({ checkedKeys: result.menus })
        //把要操作id也放进状态里保存，因为：最终下面`ok方法`要用，因此state起到`中转作用`
        this.setState({ isShowAuth: true, _id });
    };

    //新增授权 ---- ok
    handleAuthOk = async () => {
        const { _id, checkedKeys } = this.state
        const { username } = this.props
        let menus = checkedKeys
        let result = await reqAuthRole({ _id, menus, auth_name: username })
        const { status } = result
        if (status === 0) {
            message.success('授权成功')
            this.getRoleList()
            this.setState({ isShowAuth: false })
        } else {
            message.error('授权失败')
        }

    };
    handleAuthCancel = () => {
        this.setState({ isShowAuth: false });
    };

    //  -------------------tree---------star-----------------------


    onCheck = checkedKeys => {
        this.setState({ checkedKeys });
    };



    renderTreeNodes = data =>
        data.map(item => {
            if (item.children) {
                return (
                    <TreeNode title={item.title} key={item.key} dataRef={item}>
                        {this.renderTreeNodes(item.children
                        )}
                    </TreeNode>
                );
            }
            return <TreeNode key={item.key} {...item} />;
        });
    //  -------------------tree---------end-----------------------

    render() {

        const dataSource = this.state.roleList
        const columns = [
            {
                title: '角色名称',
                dataIndex: 'name',
                key: 'name',
                width: "10%"
            },
            {
                title: '创建时间',
                dataIndex: 'create_time',
                key: 'create_time',
                align: 'center',
                render: (time) => {
                    return dayjs(time).format('YYYY年 MM月DD日 HH:mm:ss')
                }
            },
            {
                title: '授权时间',
                dataIndex: 'auth_time',
                key: 'auth_time',
                align: 'center',
                //【注意】如果time为undefined(请求回来的数据没有auth_time，因为auth_time需要点击“权限操作”)，
                // 那么就是当前时间戳，所以要做判断
                render: (time) => time ? dayjs(time).format('YYYY年 MM月DD日 HH:mm:ss') : ""
            },
            {
                title: '授权人',
                dataIndex: 'auth_name',
                key: 'auth_name',
                width: "10%",
                align: 'center'
            },
            {
                title: '操作',
                key: 'operation',
                width: '15%',
                align: 'center',
                render: (item) => {
                    return <Button onClick={() => { this.showAuthModal(item._id) }} type='link'>权限操作</Button>
                }
            },
        ];

        const treeData = this.state.menuList
        return (
            <>
                <Card title={<Button onClick={this.showAddModal} type='primary' style={{ borderRadius: "5px" }}><PlusOutlined />新增角色</Button>}>
                    <Table
                        dataSource={dataSource}
                        columns={columns}
                        bordered={true}
                        rowKey="_id"
                        pagination={{
                            total: this.state.total,
                            pageSize: PAGE_SIZE,
                            current:this.state.current,
                            onChange: this.getRoleList //pagination里的onChange事件的回调(a)=>{ } 参数a就是当前在第几页
                        }}
                    />;
                </Card>
                {/* 新增角色模态框 */}
                <Modal
                    visible={this.state.isShowAdd}
                    title="添加角色"
                    onOk={this.handleAddOk}
                    onCancel={this.handleAddCancel}
                    okText="确认"
                    cancelText="取消"
                >
                    <Form
                        name="role"
                        ref={c => this.form = c}
                    >
                        <Item
                            label="角色名称"
                            name="roleName"   //name属性的值 -----> 同一验证表单value.roleName
                            rules={[{ required: true, message: '请填写角色名称!' }]}
                        >
                            <Input />
                        </Item>
                    </Form>
                </Modal>
                {/* 新增权限模态框 */}
                <Modal
                    visible={this.state.isShowAuth}
                    title="新增权限"
                    onOk={this.handleAuthOk}
                    onCancel={this.handleAuthCancel}
                    okText="确认"
                    cancelText="取消"
                >
                    <Form
                        name="auth"
                    >
                        <Item>
                            <Tree
                                checkable       //允许选择
                                onCheck={this.onCheck}
                                checkedKeys={this.state.checkedKeys}
                                defaultExpandAll   //默认展开所有节点
                            >
                                <TreeNode title="平台功能" key="top" >
                                    {this.renderTreeNodes(treeData)}
                                </TreeNode>
                            </Tree>
                        </Item>
                    </Form>
                </Modal>
            </>
        )
    }
}

export default connect(
    state => ({ username: state.userInfo.user.username }),
    {}
)(Role)
